package com.hulk.rpc.remote;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.hulk.rpc.invoke.Invoker;
import com.hulk.rpc.param.MethodParam;
import com.hulk.rpc.transport.client.App;

import java.util.concurrent.CompletableFuture;

/**
 * @author xuxukang
 * @date 2019-04-27 15:00
 */
public interface RemoteInterface {

  Log logger = LogFactory.getCurrentLogFactory().getLog(RemoteInterface.class);

  App getApp();

  default CompletableFuture<?> $remote_execute(int methodId, long timeout, MethodParam methodParam,
                                               Invoker<CompletableFuture<?>> failoverInvoker) {
    try {
      return getApp().execute(methodId, timeout, methodParam, failoverInvoker);
    } catch (Exception e) {
      if (logger.isWarnEnabled()) {
        logger.warn("远程调用发生错误");
      }

      if (failoverInvoker == null) {
        return CompletableFuture.failedFuture(e);
      } else {
        if (logger.isInfoEnabled()) {
          logger.info("远程调用发生错误，使用本地回退方法执行");
        }

        return failoverInvoker.invoke(methodParam);
      }
    }
  }

  default CompletableFuture<?> $remote_ignore() {
    return CompletableFuture.failedFuture(new RemoteException("method ignore exception", false));
  }

}
